/**
 * Created by sun on 2015/3/12.
 */
package com.jbm;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.lang.reflect.Method;

public class JSONDecoder extends CumulativeProtocolDecoder
{
//    private static final Logger LOGGER = Logger.getLogger(GDDecoder.class);

	private final String charset;

	public JSONDecoder(String charset)
	{
		this.charset = charset;
	}

	protected boolean doDecode(IoSession session, IoBuffer in,
	                           ProtocolDecoderOutput out) throws Exception
	{
		if (in.remaining() >= 4)
		{
			in.mark();

			int len = 0;
			byte[] blen = new byte[4];
			in.get(blen);
			len = (int) ((blen[3] & 0xFF)
					| ((blen[2] & 0xFF) << 8)
					| ((blen[1] & 0xFF) << 16)
					| ((blen[0] & 0xfF) << 24));

			if (len > in.remaining())
			{// 如果消息内容不够，则重置，相当于不读取size
				in.reset();
				return false;// 接收新数据，以拼凑成完整数据
			} else
			{
				byte[] bbIn = new byte[len];

				in.get(bbIn, 0, len);

				String to = new String(bbIn,"UTF-8");

				out.write(to);

				if (in.remaining() > 0)
				{// 如果读取内容后还粘了包，就让父类再给一次，进行下一次解析
					// System.out.println("package left="+in.remaining()+" data="+in.toString());
				}
				return true;// 这里有两种情况1：没数据了，那么就结束当前调用，有数据就再次调用
			}
		}

		return false;// 处理成功，让父类进行接收下个包
	}
}
